<template>
  <div style="margin-top: 20px;">
    <el-row>
      <el-input v-model="input" placeholder="请输入姓名" style="width: 300px"/>&nbsp;
      <el-button icon="el-icon-search" type="primary" @click="querySearch">查询</el-button>
      <el-button icon="el-icon-circle-plus-outline" type="warning" @click="showFormAdd">新增</el-button>
    </el-row>
    <div>
      <el-table
        v-loading="loading"
        :data="tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)"
        border
      >
        <el-table-column
          fixed
          label="序号"
          prop="id"
        />
        <el-table-column
          label="回访日期"
          prop="return_Visit_Date"
        />
        <el-table-column
          label="被干预人员"
          prop="name"
        />
        <el-table-column
          label="回访人员"
          prop="user_Name"
        />
        <el-table-column
          label="方式"
          prop="return_visit_method"
        />
        <el-table-column
          label="回访内容"
          prop="visit_Content"
        />
        <el-table-column
          label="反馈信息"
          prop="feedback"
        />
        <el-table-column
          label="处理结果"
          prop="result"
        />
        <el-table-column
          fixed="right"
          label="操作"
          width="300"
        >
          <template v-slot="scope">
            <el-button icon="el-icon-edit" size="small" type="warning" @click="showEditForm(scope.row.id)">编辑
            </el-button>
            <el-button icon="el-icon-delete" size="small" type="danger" @click="delById(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[2, 5, 10, 15, 20]"
        :total="tableData.length"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog :visible.sync="showForm">
      <el-tabs v-model="activeName">
        <el-tab-pane label="基本信息" name="first">
          <el-form ref="ruleForm" :inline="true" :model="ruleForm" :rules="rules" label-width="100px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="被干预人" prop="name">
                  <el-input v-model="ruleForm.name" @input="findidByName"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="档案号" prop="id">
                  <el-input v-model="ruleForm.id" :readonly="true"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="回访日期" prop="date">
                  <el-date-picker
                    v-model="ruleForm.date"
                    placeholder="选择日期"
                    style="width:86%;"
                    type="date"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="具体时间" prop="time">
                  <el-time-picker v-model="ruleForm.time" placeholder="选择时间" style="width:86%;"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="回访方式" prop="way">
                  <el-select v-model="ruleForm.way" placeholder="请选择回访方式">
                    <el-option label="电话" value="1"/>
                    <el-option label="邮件" value="2"/>
                    <el-option label="调查问卷" value="3"/>
                    <el-option label="面对面" value="4"/>
                    <el-option label="社交媒体" value="5"/>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="回访内容" prop="content">
                  <el-input v-model="ruleForm.content" style="width: 550px" type="textarea"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="反馈信息" prop="feedback">
                  <el-input v-model="ruleForm.feedback" style="width: 550px" type="textarea"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="处理结果" prop="result">
                  <el-input v-model="ruleForm.result" style="width: 550px" type="textarea"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item style="display: flex; justify-content: center;">
              <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
              <el-button @click="resetForm('ruleForm')">取消</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="附件" name="second ">
          <el-form ref="ruleFormFile" :inline="true" :model="ruleFormFile" :rules="rules" label-width="100px">
            <el-row>
              <el-col :span="24">
                <el-form-item label="主题" prop="theme">
                  <el-input v-model="ruleFormFile.theme" style="width: 550px" type="textarea"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="请选择方案" label-width="100px">
                  <el-upload
                    :before-upload="beforeUpload"
                    :on-success="handleSuccess"
                    action="api/FileUpload/saveFile"
                  >
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">文件大小不能超过10M</div>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item style="display: flex; justify-content: center;">
              <el-button type="primary" @click="submitFile">确定</el-button>
              <el-button @click="resetForm('ruleForm')">取消</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <el-dialog :visible.sync="showeditForm" title="编辑">
      <el-form ref="showFormmod" :inline="true" :model="showFormmod" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="被干预人" prop="name">
              <el-input v-model="showFormmod.name" :readonly="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="序号" prop="id">
              <el-input v-model="showFormmod.id" :readonly="true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="回访日期" prop="date">
              <el-date-picker
                v-model="showFormmod.date"
                placeholder="选择日期"
                style="width:86%;"
                type="date"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="具体时间" prop="time">
              <el-time-picker v-model="showFormmod.time" placeholder="选择时间" style="width:86%;"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="回访方式" prop="way">
              <el-select v-model="showFormmod.way" placeholder="请选择回访方式">
                <el-option label="电话" value="1"/>
                <el-option label="邮件" value="2"/>
                <el-option label="调查问卷" value="3"/>
                <el-option label="面对面" value="4"/>
                <el-option label="社交媒体" value="5"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="回访内容" prop="content">
              <el-input v-model="showFormmod.content" style="width: 550px" type="textarea"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="反馈信息" prop="feedback">
              <el-input v-model="showFormmod.feedback" style="width: 550px" type="textarea"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="处理结果" prop="result">
              <el-input v-model="showFormmod.result" style="width: 550px" type="textarea"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item style="display: flex; justify-content: center;">
          <el-button type="primary" @click="updateFollowUpDiary('showFormmod')">修改</el-button>
          <el-button @click="closeEditForm('showFormmod')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import getters from '@/store/getters'

export default {
  data() {
    return {
      loading: false,
      currentPage: 1,
      input: '',
      pageSize: 2, // 每页显示的条数
      totalNum: 10, // 总条数
      currentPages: 1,
      showForm: false, // 控制添加表单的显示状态，默认隐藏
      showeditForm: false,
      activeName: 'first',
      name: '',
      id: '',
      tableData: [{
        id: 1,
        date: '2023-08-12 19:30:09',
        bname: '张三',
        hname: '李四',
        type: '饮食干预',
        htext: '饮食状况',
        fxin: '暴食',
        chlijie: '无效'

      }],
      /* 添加对象 */
      ruleForm: {
        name: '',
        id: '',
        date: '',
        time: '',
        way: '',
        content: '',
        feedback: '',
        result: ''
      },
      ruleFormFile: {
        theme: '',
        path: ''
      },
      /* 修改对象 */
      showFormmod: {
        name: '',
        id: '',
        date: '',
        time: '',
        way: '',
        content: '',
        feedback: '',
        result: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入被干预人', trigger: 'blur' }
        ],
        id: [
          { required: true, message: '请输入档案号', trigger: 'blur' }
        ],
        date: [
          { required: true, message: '请选择回访日期', trigger: 'change' }
        ],
        time: [
          { required: true, message: '请选择具体时间', trigger: 'change' }
        ],
        way: [
          { required: true, message: '请选择回访方式', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入回访内容', trigger: 'blur' }
        ],
        feedback: [
          { required: true, message: '请输入反馈信息', trigger: 'blur' }
        ],
        result: [
          { required: true, message: '请输入回访结果', trigger: 'blur' }
        ]
      }
    }
  },
  beforeCreate() {
    console.log('beforeCreate: 页面加载前执行方法')
    axios.get('api/FollowUpDiary/findAll').then(res => {
      console.log(res)
      this.tableData = res.data.data
      console.log(this.tableData.length)
    })
  },
  mounted() {
    this.totalNum = this.tableData.length
  },
  methods: {
    handleClick(row) {
      console.log(row)
    },
    handleSizeChange(val) {
      this.pageSize = val
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      this.currentPage = val
      console.log(`当前页: ${val}`)
    },
    /**
     * 显示添加页面
     */
    showFormAdd() {
      this.showForm = true
    },
    /** 根据名称自动查询档案号 */
    findidByName(name) {
      axios.get('api/FollowUpDiary/findIdByName', { params: { name: name }}).then(res => {
        if (res.data.data.fileNumber === '无') {
          this.ruleForm.id = ''
        } else {
          this.ruleForm.id = res.data.data.fileNumber
        }
      })
    },
    /** 带条件查询分页 */
    querySearch() {
      axios.get('api/FollowUpDiary/findAll', { params: { name: this.input }})
        .then(res => {
          console.log(res)
          this.tableData = res.data.data
          console.log(this.tableData.length)
        })
        .catch(error => {
          console.error('请求出错：', error)
        })
    },
    /** 显示修改页面**/
    showEditForm(id) {
      const data = this.tableData.find((message) => message.id === id)
      this.showeditForm = true

      /** 给修改页面赋值*/
      this.showFormmod.name = data.name
      this.showFormmod.id = data.id
      this.showFormmod.date = data.return_Visit_Date.substring(0, 10)
      this.showFormmod.time = data.return_Visit_Date
      this.showFormmod.way = data.return_visit_method
      this.showFormmod.content = data.visit_Content
      this.showFormmod.feedback = data.feedback
      this.showFormmod.result = data.result
    },
    /**
     * 确认添加方法
     * @param formName
     */
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const followUpDiaryDTO = {
            name: this.ruleForm.name,
            date: this.ruleForm.date,
            time: this.ruleForm.time,
            visitId: this.ruleForm.way,
            visit_Content: this.ruleForm.content,
            feedback: this.ruleForm.feedback,
            result: this.ruleForm.result,
            intervener: getters.user_id(this.$store.state)
          }
          console.log(followUpDiaryDTO)
          // 发送 POST 请求到后端
          axios.post('/api/FollowUpDiary/saveFollowUp', followUpDiaryDTO, {
            headers: {
              'Content-Type': 'application/json'
            }
          }).then(response => {
            // 请求成功处理逻辑
            if (response.status === 200) {
              this.$message.success('提交成功!')
              // 清空表单数据
              this.$refs[formName].resetFields()
              this.querySearch()
            } else {
              this.$message.error('提交失败!')
            }
          })
            .catch(error => {
              // 异常处理逻辑
              console.error('请求出错：', error)
            })
          this.showForm = false
        } else {
          alert('error submit!!')
          return false
        }
      })
    },
    // 文件上传成功的钩子
    handleSuccess(res) {
      console.log(res.data)
      this.ruleFormFile.path = res.data
    },
    resetForm(done) {
      this.$refs[done].resetFields()
      this.showForm = false
    },
    closeEditForm(done) {
      this.showeditForm = false
      this.$refs[done].resetFields()
    },
    /** 文件预上传格式限制 */
    beforeUpload(file) {
      const isLt5M = file.size / 1024 / 1024 < 10
      if (!isLt5M) {
        console.log('文件大小超过限制')
        this.$message.error('上传的文件大小不能超过 10MB!')
        return false
      }
      return true
    },
    // 上传文件和数据
    submitFile() {
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          const formData = {
            name: this.ruleForm.name,
            date: this.ruleForm.date,
            time: this.ruleForm.time,
            visitId: this.ruleForm.way,
            visit_Content: this.ruleForm.content,
            feedback: this.ruleForm.feedback,
            result: this.ruleForm.result,
            theme: this.ruleFormFile.theme,
            path: this.ruleFormFile.path,
            intervener: getters.user_id(this.$store.state)
          }
          console.log(formData)
          axios.post('/api/FollowUpDiary/saveFileInfo', formData, {
            headers: {
              'Content-Type': 'application/json'
            }
          })
            .then(response => {
              // 请求成功处理逻辑
              if (response.status === 200) {
                this.$message.success('提交成功!')
                // 清空表单数据
                this.$refs['ruleForm'].resetFields() // 重置 'ruleForm' 引用对象的字段
                this.$refs['ruleFormFile'].resetFields() // 重置 'ruleFormFile' 引用对象的字段
                this.querySearch()
              } else {
                this.$message.error('提交失败!')
              }
            })
            .catch(error => {
              // 异常处理逻辑
              console.error('请求出错：', error)
            })
          this.showForm = false
        }
      })
    },
    /** 修改 */
    updateFollowUpDiary() {
      this.$refs['showFormmod'].validate(valid => {
        if (valid) {
          const followUpDiaryEdit = {
            name: this.showFormmod.name,
            id: this.showFormmod.id,
            date: this.showFormmod.date,
            time: this.showFormmod.time,
            visitId: this.showFormmod.way,
            visit_Content: this.showFormmod.content,
            feedback: this.showFormmod.feedback,
            result: this.showFormmod.result
          }
          console.log(followUpDiaryEdit)
          axios.post('/api/FollowUpDiary/updateFollowUpDiaryById', followUpDiaryEdit, {
            headers: {
              'Content-Type': 'application/json'
            }
          }).then(response => {
            // 请求成功处理逻辑
            if (response.status === 200) {
              this.$message.success('修改成功!')
              // 清空表单数据
              this.$refs['showFormmod'].resetFields()
              this.querySearch()
            } else {
              this.$message.error('修改失败!')
            }
          })
            .catch(error => {
              // 异常处理逻辑
              console.error('请求出错：', error)
            })
        } else {
          alert('error submit!!')
          return false
        }
      })
      this.showeditForm = false
    },
    /** 删除 */
    delById(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.post('/api/FollowUpDiary/delFollowUpDiary', { id: id }, {
          headers: {
            'Content-Type': 'application/json'
          }
        }).then(() => {
          this.querySearch()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>
